import { getToken } from '@/utils/cookies'
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import HomeView from '../views/Home/HomeView.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      auth: true
    }
  },
  {
    path: '/login',
    name: 'login',

    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import('../views/Login/EntryView.vue')
  },
  {
    path: '/album',
    name: 'album',
    component: () => import('../views/Album/AlbumView.vue'),
    meta: {
      auth: true
    }
  },
  {
    path: '/picture',
    name: 'picture',
    component: () => import('../views/Album/PictureView.vue'),
    meta: {
      auth: true
    }
  },
  {
    path: '/recycler',
    name: 'recycler',
    component: () => import('../views/Recycler/RecyclerView.vue'),
    meta: {
      auth: true
    }
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/UserCenter/UserCenterView.vue'),
    meta: {
      auth: true
    },
    children: [
      {
        path: 'info',
        name: 'info',
        component: () => import('../views/UserCenter/components/InfoView.vue')
      },
      {
        path: 'password',
        name: 'password',
        component: () => import('../views/UserCenter/components/PasswordView.vue')
      },
      {
        path: 'tag',
        name: 'tag',
        component: () => import('../views/UserCenter/components/TagView.vue')
      },
      {
        path: 'record',
        name: 'record',
        component: () => import('../views/UserCenter/components/RecordView.vue')
      },
      {
        path: '',
        redirect: '/user/info'
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// export function resetRouter() {
//   const newRouter = createRouter();
//   (router as any).matcher = (newRouter as any).matcher // reset router
// }

// 路由守卫
router.beforeEach((to, from, next) => {

  // to要跳转到的路径
  // from从哪个路径来
  // next往下执行的回调
  // 在localStorage中获取token
  const token = getToken();

  // 判断该页面是否需要登录
  if (to.meta.auth) {

    // 如果token存在直接跳转
    if (token) {
      next()
    } else {

      // 否则跳转到login登录页面
      next({
        path: '/login',

        // 跳转时传递参数到登录页面，以便登录后可以跳转到对应页面
        query: {
          redirect: to.fullPath
        }
      })
    }
  } else {

    // 如果不需要登录，则直接跳转到对应页面
    next()
  }
})

export default router
